package com.yisu.expressway.onedollar.presenter.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.OrderShowItem;
import com.yisu.expressway.onedollar.presenter.IOrderShowPresenter;
import com.yisu.expressway.onedollar.view.IOrderShowView;

import android.content.Context;

/**
 * Created by Kaven on 2016/12/15.
 */

public class OrderShowPresenterImp implements IOrderShowPresenter {
    private Context mContext;
    private IOrderShowView mView;
    private List<OrderShowItem> mData;

    public OrderShowPresenterImp(Context mContext, IOrderShowView mView) {
        this.mContext = mContext;
        this.mView = mView;
    }

    @Override
    public void fetchMore(long barcode, int start, int pageSize) {
        if (pageSize <= 0) {
            return;
        }
        Map<String, Object> params = new HashMap();

        int pageIndex = getPageIndex(start, pageSize);

        params.put("pageindex", pageIndex);
        params.put("pagesize", pageSize);
        params.put("barcode", barcode);
        ApiClientHelper.postApi(ApiSetting.getOrderShowList(),
                new TypeToken<List<OrderShowItem>>() {
                }, new JSONObject(params),
                new Response.Listener<ApiResult<List<OrderShowItem>>>() {
                    @Override
                    public void onResponse(ApiResult<List<OrderShowItem>> result) {
                        if (!result.success) {
                            mView.showToast(result.getMsg());
                            return;
                        }
                        mData = result.getResult();
                        mView.refreshView();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        mView.showToast(volleyError.getMessage());
                        mView.refreshView();
                    }
                }, mContext);
    }

    @Override
    public void init() {

    }

    @Override
    public List<OrderShowItem> getOrderShowList() {
        return mData;
    }

    private int getPageIndex(int start, int pageSize) {
        int round = start / pageSize;

        return round + 1;
    }
}
